package com.amkai.aes.webservice.binary.objecthandler.inventory;

import java.io.Serializable;
import java.util.List;

import com.amkai.aes.aescommon.exceptions.inventory.VendorDeleteException;
import com.amkai.aes.aescommon.service.binary.job.inventory.VendorOrderInformationJob;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class VendorOrderInformationHandler implements JobObjectHandler<VendorOrderInformationJob, Serializable, Serializable> {

	@Override
	public Serializable process(VendorOrderInformationJob job, Serializable object) throws Exception {
		// TODO Auto-generated method stub
		Serializable result = null;
		if (job != null && !job.isDeleted()) {
				result = deleteVendor(job.getVendorId());
		}
		return result;
		
	}

	private String deleteVendor(long vendorId) throws Exception {			
			List result = null;
			SessionManager sm = SiteManager.Start();
			String message = "Reference found in Adjustment!";
			result = sm.execute("from TransactionDescriptor td where td.vendorOrderInformation.id = :void").setLong("void", vendorId).list();
			if (result == null || (result != null && result.size() == 0)){
				result = sm.execute("from OrderRequisitionLine orl where orl.vendorOrderInformation.id = :void").setLong("void", vendorId).list();
				message = "Reference found in Order Requisition!";
			}
			if (result == null|| (result != null && result.size() == 0)){
				result = sm.execute("from PurchaseOrderLine prl where prl.vendorOrderInformation.id = :void").setLong("void", vendorId).list();
				message = "Reference found in Purchase Order!";
			}
			if (result == null || (result != null && result.size() == 0)){
				sm.execute("delete from VendorOrderInformation voi where voi.id = :void").setLong("void", vendorId).executeUpdate();
				message = null;
			}else{
				message = "Can't delete vendor! " + message; 
			}
			return message;
	}

}
